Fascination With Iterators

Limbic Region on 2004-09-23T23:59:11

After declaring I was taking a programming hiatus only a few days ago, I have written two pieces of code I am fairly proud of. The first was an efficient way to process every line in 1 file against every line in another file without slurping the files into memory.

The second was an iterator for x size subsets of y

#!/usr/bin/perl use strict; use warnings;

my $iter = combo( 3 , 1 .. 5 ); while ( my @combo = $iter->() ) { print "@combo\n"; }

sub combo { my $by = shift; return sub { () } if ! $by || $by =~ /\D/ || @_ < $by; my @list = @_;

my @position = (0 .. $by - 2, $by - 2); my @stop = @list - $by .. $#list; my $end_pos = $#position; my $done = undef;

return sub { return () if $done; my $cur = $end_pos; { if ( ++$position[ $cur ] > $stop[ $cur ] ) { $position[ --$cur ]++; redo if $position[ $cur ] > $stop[ $cur ]; my $new_pos = $position[ $cur ]; @position[ $cur .. $end_pos ] = $new_pos .. $new_pos + $by; } } $done = 1 if $position[0] == $stop[0]; return @list[ @position ]; } } __END__ 1 2 3 1 2 4 1 2 5 1 3 4 1 3 5 1 4 5 2 3 4 2 3 5 2 4 5 3 4 5

Notice that the only looping construct in the entire thing is a bare block. It is very fast ;-)